public class SolutionLCP51 {

    int ans=-1;
    int hunCur=0;
    int deliCur=0;
    boolean[] use;

    public int perfectMenu(int[] materials, int[][] cookbooks, int[][] attribute, int limit) {
        use=new boolean[cookbooks.length];
        work(materials,cookbooks,attribute,limit);
        return ans;
    }

    void work(int[] materials, int[][] cookbooks, int[][] attribute, int limit){
        if (hunCur>=limit && deliCur>ans){
            ans=deliCur;
        }
        for (int j=0;j<cookbooks.length;j++) {
            if (!use[j]) {
                boolean can = true;
                for (int i = 0; i < 5; i++) {
                    if (materials[i] < cookbooks[j][i]) {
                        can = false;
                        break;
                    }
                }
                if (can) {
                    for (int i = 0; i < 5; i++) {
                        materials[i] -= cookbooks[j][i];
                    }
                    hunCur += attribute[j][1];
                    deliCur += attribute[j][0];
                    use[j]=true;
                    work(materials, cookbooks, attribute, limit);
                    use[j]=false;
                    for (int i = 0; i < 5; i++) {
                        materials[i] += cookbooks[j][i];
                    }
                    hunCur -= attribute[j][1];
                    deliCur -= attribute[j][0];
                }
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new SolutionLCP51().perfectMenu(new int[]{3,2,4,1,2},new int[][]{{1,1,0,1,2},{2,1,4,0,0},{3,2,4,1,0}},new int[][]{{3,2},{2,4},{7,6}},5));
    }
}
